//
//  AFHTTPRequestOperation+KLRACSupport.m
//  KoalaUtilKit
//
//  Created by Tommy on 15/1/8.
//  Copyright (c) 2015年 Koala Team. All rights reserved.
//

#import "AFHTTPRequestOperation+KLRACSupport.h"
#import "RACSubscriber+KLProgressSupport.h"
#import <objc/runtime.h>

static char KLHttpProgressSignalKey;

@implementation AFHTTPRequestOperation (KLRACSupport)

- (RACSignal *)klrac_start{
    [self start];
    [self klrac_overrideHTTPProgressBlock];
    return [self rac_overrideHTTPCompletionBlock];

}

- (RACSignal *)klrac_progressSignal{
    return objc_getAssociatedObject(self, &KLHttpProgressSignalKey);
}

- (void)setKlrac_progressSignal:(RACSubject*)progress{
    objc_setAssociatedObject(self, &KLHttpProgressSignalKey, progress, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


- (RACSignal *)klrac_overrideHTTPProgressBlock{
    RACReplaySubject *subject = [RACReplaySubject replaySubjectWithCapacity:1];
    [subject setNameWithFormat:@"-klrac_start: %@", self.request.URL];
    
    [self setKlrac_progressSignal:subject];
    if ([self respondsToSelector:@selector(setUploadProgressBlock:)]) {
        
#ifdef RAFN_MAINTAIN_COMPLETION_BLOCKS
        void (^oldUploadProgress)() = self.uploadProgress;
#endif
        [(AFHTTPRequestOperation*)self setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
            CGFloat progress = totalBytesWritten>0?(CGFloat)bytesWritten/totalBytesWritten:0;
            [subject sendProgress:progress];
#ifdef RAFN_MAINTAIN_COMPLETION_BLOCKS
            if (oldUploadProgress) {
                oldUploadProgress(bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
            }
#endif
        }];
    }
    
    if ([self respondsToSelector:@selector(setDownloadProgressBlock:)]) {
        
#ifdef RAFN_MAINTAIN_COMPLETION_BLOCKS
        void (^oldDownloadProgress)() = self.downloadProgress;
#endif
        [(AFHTTPRequestOperation*)self setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            CGFloat progress = totalBytesRead>0?(CGFloat)bytesRead/totalBytesRead:0;
            [subject sendProgress:progress];
#ifdef RAFN_MAINTAIN_COMPLETION_BLOCKS
            if (oldDownloadProgress) {
                oldDownloadProgress(bytesRead,totalBytesRead,totalBytesExpectedToRead);
            }
#endif
        }];
    }

    
    return subject;
}

@end
